// pages/cart/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
Page({

  data: {
    cardList: [],
    isAllActived: false, // 全选
    isHasActived: false, // 是否有选择的商品，用于按钮的置灰判断
    totalPrice: 0,
  },

  onChange(e) {
    const id = e.target.dataset.id;
    const num = e.detail;
    const cardList = this.data.cardList;
    const idx = cardList.findIndex(item => item.id == id);
    cardList[idx].num = num;
    wx.setStorageSync('card-data', cardList)
    this.setData({
      totalPrice: this.sumTotalPrice(cardList)
    })
  },

  checkedItem(e) {
    const id = e.currentTarget.dataset.id;
    const actived = e.currentTarget.dataset.value;
    const cardList = this.data.cardList;
    const idx = cardList.findIndex(item => item.id == id);
    cardList[idx].actived = actived;
    const isAllActived = cardList.every(item => item.actived);
    const isHasActived = cardList.some(item => item.actived);
    wx.setStorageSync('card-data', cardList)
    this.setData({
      cardList,
      isAllActived,
      isHasActived,
      totalPrice: this.sumTotalPrice(cardList)
    })
  },

  // 全选
  checkedAllItem(e) {
    const actived = e.currentTarget.dataset.value;
    const cardList = this.data.cardList;
    cardList.map(item => {
      item.actived = actived
    })
    wx.setStorageSync('card-data', cardList)
    this.setData({
      cardList,
      isAllActived: actived,
      isHasActived: actived,
      totalPrice: this.sumTotalPrice(cardList)
    })
  },

  sumTotalPrice(cardList) {
    let totalPrice = 0;
    cardList.forEach(item => {
      if (item.actived) {
        totalPrice += Number(item.price) * Number(item.num)
      }
    })
    return totalPrice;
  },

  // 去结算
  onClickButton() {
    wx.navigateTo({
      url: '../order-confirm/order-confirm',
    })
  },

  onShow() {
    const cardList = wx.getStorageSync('card-data');
    const isAllActived = cardList.every(item => item.actived);
    const isHasActived = cardList.some(item => item.actived);
    this.setData({
      cardList,
      totalPrice: this.sumTotalPrice(cardList),
      isAllActived,
      isHasActived
    })
  },

})